package it.fc.action.users;

import fc.utils.FcCostanti;
import it.fc.action.FcAction;
import it.fc.bean.UserBean;
import it.fc.exceptions.FcException;
import it.fc.service.interfaces.IDbService;

import org.apache.log4j.Logger;

public class LoginAction extends FcAction {

    private static final long serialVersionUID = -4780912205728526376L;
    private static Logger     log              = Logger.getLogger(LoginAction.class);

    private String            username;
    private String            password;

    @Override
    public String execute() throws Exception {

        log.debug("Login action EXECUTE");

        if (!doLogin()) {
            addActionError(getText("user.error"));
            return INPUT;
        }

      return SUCCESS;
    }

    @SuppressWarnings("unchecked")
    private boolean doLogin() throws FcException {

        log.debug("Calling doLogin()");
       
        IDbService dbMan = getDbService();
        
        UserBean current = dbMan.findUserByUsername(getUsername());

        if (current != null) { // user trovato
            if (current.getPassword().equals(getPassword())) {
                getSession().put(FcCostanti.SESSION_USER, current);
                log.debug("User : " + getUsername() + " has logged in...");
                return true;
            } else {
                return false;
            }
        } else {
            return false;
        }
    }

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

}
